<?php

namespace app\mini\controller;

use app\admin\model\PersonModel;
use app\admin\model\Policy;
use app\admin\model\ShopModel;
use app\admin\model\StoreModel;
use app\admin\model\User;
use app\common\controller\Common;
use app\crm\model\Customer;
use app\mini\model\CustomerPointGoods;
use app\mini\model\CustomerPointGoodsBuy;
use app\mini\model\CustomerPointGoodsDetail;
use app\mini\model\CustomerPointGoodsImg;
use app\mini\model\CustomerPointLogModel;
use app\mini\model\CustomerPointModel;
use app\mini\model\CustomerPointOriginModel;
use app\mini\validate\CustomerPoint as CustomerPointValidate;
use app\shop\model\Goods;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use OSS\OssClient;
use think\facade\Db;
use think\facade\Filesystem;


class CustomerPoint extends Common
{
    /**
     * 获取积分列表
     *
     * @return \think\response\Json
     */
    public function getEarnPointList()
    {
        $param = request()->param();
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $customerPoint = new CustomerPointModel();
        $where = [];
        $max = $param['max']??0;
        $min = $param['min']??0;
        if(!empty($shopIds))
        {
            array_push($where,['b.shop_id','in',$shopIds]);
        }
        if(!empty($param['customer_name']))
        {
            array_push($where,['b.customer_name','like','%'.$param['customer_name'].'%']);
        }
        if(!empty($param['shop_id']))
        {
            array_push($where,['b.shop_id','=',$param['shop_id']]);
        }
        if(!empty($param['telephone']))
        {
            array_push($where,['b.telephone','=',$param['telephone']]);
        }
        if(!empty($param['min'])||!empty($param['max']))
        {
            if($max>0)
            {
                array_push($where,['a.total','between',[$min,$max]]);
            }else{
                array_push($where,['a.total','>=',$min]);
            }
        }
        $dataCount = $customerPoint->alias('a')
            ->join('customer b','a.customer_id = b.id','left')
            ->join('shop c','b.shop_id = c.shop_id','left')
            ->where($where)->count();
        $result = $customerPoint->alias('a')
            ->join('customer b','a.customer_id = b.id','left')
            ->join('shop c','b.shop_id = c.shop_id','left')
            ->where($where)
            ->page($param['page'], $param['limit'])
            ->order('a.created_at','desc')->column('a.customer_id,c.shop_name,b.customer_name,b.telephone,a.total');
        return $this->success($result, '获取成功', $dataCount);
    }

    /**
     * 获取客户个人积分和积分获取记录
     *
     * @return \think\response\Json
     */
    public function getPersonPoint()
    {
        $param = request()->param();
        $id = $param['id'];
        $customerPoint = new CustomerPointModel();
        $customerPointLog = new CustomerPointLogModel();
        $now = $customerPoint->where('customer_id','=',$id)->find();
        $log = $customerPointLog->alias('a')
            ->where('a.customer_id','=',$id)
            ->join('customer_point_origin b','b.id = a.origin_id','left');
        $total = $log->count();
        if(!empty($param['page'])&&!empty($param['limit']))
        {
            $log = $log->page($param['page'], $param['limit']);
        }
        $log = $log->order('created_at','desc')->column('b.change_type,a.point as num,b.message,a.created_at');
        $data=[];
        $data['total'] = $now['total']??0;
        $data['log'] = [];
        foreach ($log as $value)
        {
            $temp = [];
            if($value['change_type']==1)
            {
                $temp['num']=$value['num'];
            }else{
                $temp['num']='-'.$value['num'];
            }
            $temp['message']=$value['message'];
            $temp['created_at']=date('Y-m-d H:i:s',$value['created_at']);
            array_push($data['log'],$temp);
        }
        return $this->success($data, '获取成功',$total);
    }

    /**
     * 积分变动
     *
     * @return string|\think\response\Json|void
     */
    public function pointChange()
    {
        $param = request()->param();
        Db::startTrans();
        try {
            $res = CustomerPointModel::pointChange($param['customer_id'],$param['origin_id']);
            Db::commit();
            return $this->success([], '积分变动完成');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }


    /**
     * 积分来源列表
     *
     * @return \think\response\Json
     */
    public function pointOriginList()
    {
        $param = request()->param();
        $total = CustomerPointOriginModel::count();
        $pointOrigin = CustomerPointOriginModel::page($param['page'], $param['limit'])->select()->toArray();
        $data = [];
        foreach ($pointOrigin as $key => $value)
        {
            $temp = [];
            $temp['id'] = $value['id'];
            if($value['change_type'] == 1)
            {
                $temp['num'] = '+'.$value['num'];
            }else{
                $temp['num'] = '-'.$value['num'];
            }
//            $temp['num'] = $value['num']?'+'.$value['num']:'-'.$value['num'];
            $temp['message'] = $value['message'];
            $temp['status'] = $value['status']?"启用":"禁用";
            array_push($data,$temp);
        }
        return $this->success($data, '获取成功',$total);
    }

    /**
     * 新增积分来源
     *
     * @return \think\response\Json
     */
    public function addPointOrigin()
    {
        $param = request()->param();
        $data = [];
        if($param['num']>=0)
        {
            $data['change_type'] = 1;
        }else{
            $data['change_type'] = 2;

        }
        $data['num'] = abs($param['num'])??0;
        $data['message'] = $param['message']??"";
        $res = CustomerPointOriginModel::insertGetId($data);
        if($res)
        {
            return $this->success([],'添加完成');
        }else{
            return $this->failed(400, "添加失败");
        }
    }

    /**
     * 修改积分来源
     *
     * @return \think\response\Json
     */
    public function updatePointOrigin()
    {
        $param = request()->param();
        $origin = CustomerPointOriginModel::find($param['id']);
        if(!$origin)
        {
            return $this->failed(400, "积分来源不存在");
        }
        $origin->num = abs($param['num'])??0;
//        $origin->status = $param['status']??1;
        if($param['num']>=0)
        {
            $origin->change_type=1;
        }else{
            $origin->change_type=2;
        }
        $origin->message = $param['message']??"";
        $res = $origin->save();
        if($res)
        {
            return $this->success([],'编辑完成');
        }else{
            return $this->failed(400, "编辑失败");
        }

    }

    /**
     * 积分商品列表
     *
     * @return \think\response\Json
     */
    public function pointGoodsList()
    {
        $param = request()->param();
        $name = $param['name']??"";
        $status = $param['status']??0;
        $where = [];
        if(!empty($name))
        {
            array_push($where,['goods_name','like','%'.$name.'%']);
        }
        if(!empty($status))
        {
            array_push($where,['status','=',$status]);
        }
        $total = CustomerPointGoods::where($where)->count();
        $result = CustomerPointGoods::where($where)->page($param['page'], $param['limit'])->select()->toArray();
        foreach ($result as $key => $value)
        {
            $result[$key]['url'] = CustomerPointGoodsImg::where([
                'point_goods_id'=>$value['id'],
                'status'=>1,
                'type'=>1,
            ])->value('url')??"";
        }
        return $this->success($result,'获取完成',$total);

    }

    /**
     * 新增积分产品
     *
     * @return string|\think\response\Json
     */
    public function addPointGoods()
    {
        $param = request()->param();
        $name = $param['name']??"";
        $status = $param['status']??2;
        $price = $param['price']??0;
        $desc = $param['desc']??"";
        $type = $param['type']??0;
        $goodsOrCoupon = $param['goods_or_coupon']??[];
        $goodsImage = $param['files'];
        Db::startTrans();
        try {
            $origin = new CustomerPointOriginModel();
            $origin->message = $name;
            $origin->num = $price;
            $origin->change_type = 2;
            $origin->save();
            $pointGoods = new CustomerPointGoods();
            $pointGoods->goods_name = $name;
            $pointGoods->price = $price;
            $pointGoods->type = $type;
            $pointGoods->message = $desc;
            $pointGoods->status = $status;
            $pointGoods->origin_id = $origin->id;
            $pointGoods->save();
            $insertData = [];
            foreach ($goodsOrCoupon as $value)
            {
                $temp = [
                    'object_id'=>$value['id'],
                    'number'=>$value['number'],
                    'point_goods_id'=>$pointGoods->id,
                    'type'=>$type,
                    'service_number'=>$value['service_number']??0,
                    'service_days'=>$value['service_days']??0,
                ];
                array_push($insertData,$temp);
            }
            $goodsDetail = new CustomerPointGoodsDetail();
            $goodsDetail->saveAll($insertData);
            $insertData = [];
            foreach ($goodsImage as $value)
            {
                $temp = [
                    'point_goods_id'=>$pointGoods->id,
                    'url'=>$value['url'],
                    'type'=>$value['type'],
                    'status'=>1
                ];
                array_push($insertData,$temp);
            }
            $goodsImg = new CustomerPointGoodsImg();
            $goodsImg->saveAll($insertData);
            Db::commit();
            return $this->success([],'新增完成');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

    /**
     * 修改商品状态
     *
     * @return \think\response\Json
     */
    public function pointGoodsStatusUpdate()
    {
        $param = request()->param();

        $id = $param['id'];
        $pointGoods = CustomerPointGoods::find($id);
        if(empty($pointGoods))
        {
            return $this->failed(400, "积分产品不存在");
        }
        if($pointGoods->status == 1)
        {
            $pointGoods->status =2;
        }else{
            $pointGoods->status =1;
        }
        $res = $pointGoods->save();
        if($res)
        {
            return $this->success([],'编辑完成');
        }else{
            return $this->failed(400, "编辑失败");
        }
    }

    /**
     * 积分商品详情
     *
     * @return \think\response\Json
     */
    public function getPointGoodsDetail()
    {
        $param = request()->param();
        $id = $param['id'];
        $info = CustomerPointGoods::find($id);
        $where = [];
        array_push($where,['b.point_goods_id','=',$id]);
        array_push($where,['b.type','=',1]);
        $goods = Db::name('shop_goods')->alias('a')
            ->join('customer_point_goods_detail b','b.object_id = a.id','left')
            ->where($where)->column('a.name,b.number,b.type,b.service_number,b.service_days');
        foreach ($goods as $key => $value)
        {
            if($value['service_days']==0&&$value['service_number']==0)
            {
                $goods[$key]['type_name']= "商品";
            }else{
                $goods[$key]['type_name']= "服务";
            }
        }
        array_push($where,['b.point_goods_id','=',$id]);
        array_push($where,['b.type','=',2]);
        $coupon = Db::name('coupon')->alias('a')
            ->join('customer_point_goods_detail b','b.object_id = a.id','left')
            ->where($where)->column('a.name,b.number,b.type,b.service_number,b.service_days');
        foreach ($coupon as $key => $value)
        {
            if($value['type']==1)
            {
                $coupon[$key]['type_name']= "满减券";
            }
            if($value['type']==2)
            {
                $coupon[$key]['type_name']= "满赠券";
            }
            if($value['type']==3)
            {
                $coupon[$key]['type_name']= "兑换券";
            }
        }
        $result = array_merge($goods,$coupon);
        $where = [];
        array_push($where,['point_goods_id','=',$id]);
        array_push($where,['type','=',1]);
        $banner = CustomerPointGoodsImg::where($where)->select()->toArray();
        $where = [];
        array_push($where,['point_goods_id','=',$id]);
        array_push($where,['type','=',2]);
        $image = CustomerPointGoodsImg::where($where)->select()->toArray();

        return $this->success([
            'info'=>$info,
            'object_list'=>$result,
            'banner'=>$banner,
            'image'=>$image
        ],'获取完成');
    }

    /**
     * 上传积分商品图
     *
     * @return \think\response\Json
     */
    public function uploadPointGoodsImage()
    {
        $file = request()->file('file');
        $saveName = Filesystem::disk('public')->putFile('image', $file);
        $accessKeyId = "LTAI4FopKKqp8ZE7qMh7x8rL";
        $accessKeySecret = "QU8minZbbZFXsHl9EHq8BmQo3S27lV";
        $endpoint = "oss-cn-zhangjiakou-internal.aliyuncs.com";
        $bucket = "xinyiinfors";
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $oss_url = substr($saveName, 6);
        $content = './storage/' . $saveName;// 服务器路径
        $object = "xy_img/" . $oss_url;// OSS路径
        $ossClient->uploadFile($bucket, $object, $content);// 上传
        unlink($content);
        return $this->success([
            'url'=>'http://xinyiinfors.oss-cn-zhangjiakou.aliyuncs.com/'.$object,
        ],"成功");

    }

    /**
     * 编辑积分商品
     *
     * @return \think\response\Json
     */
    public function editPointGoods()
    {
        $param = request()->param();
        $id = $param['id'];
        $cancel = $param['cancel'];
        $bannerNew = $param['banner_new'];
        $imageNew = $param['image_new'];
        if (!empty($cancel)) {
            $res = CustomerPointGoodsImg::destroy($cancel);
            if (!$res) {
                return $this->failed(400, "编辑失败");
            }
        }
        $insertData = [];
        foreach ($bannerNew as $value) {
            $temp = [
                'url' => $value['url'],
                'type' => 1,
                'point_goods_id' => $id
            ];
            array_push($insertData, $temp);
        }
        foreach ($imageNew as $value) {
            $temp = [
                'url' => $value['url'],
                'type' => 2,
                'point_goods_id' => $id
            ];
            array_push($insertData, $temp);
        }
        if (!empty($insertData))
        {
            $image = new CustomerPointGoodsImg;
            $res = $image->saveAll($insertData);
            if(!$res)
            {
                return $this->failed(400, "编辑失败");
            }
        }
        return $this->success([],"成功");
    }

    /**
     * 客户购买积分商品
     *
     * @return string|\think\response\Json
     */
    public function buy()
    {
        $param = request()->param();
        try {
            $validate  = new CustomerPointValidate();
            if (!$validate->scene('buy')->check($param)) {
                return $this->failed(300, $validate->getError());
            }
        }catch (\Exception $e) {
            return $this->error = $e->getMessage();
        }
        $customerId = $param['customer_id'];
        $pointGoodsId = $param['point_goods_id'];
        $pointGoods = CustomerPointGoods::find($pointGoodsId);
        if(empty($pointGoods))
        {
            return $this->failed(400, "积分商品不存在");

        }
        $customerPoint = CustomerPointModel::where('customer_id','=',$customerId)->find();
        if(empty($customerPoint)||$customerPoint->total<$pointGoods->price)
        {
            return $this->failed(400, "积分不足");
        }
        Db::startTrans();
        try {
            $customerPointGoodsBuy = new CustomerPointGoodsBuy();
            $customerPointGoodsBuy->save([
                'point_goods_id'=>$pointGoodsId,
                'customer_id'=>$customerId,
                'status'=>1
            ]);
            CustomerPointModel::pointChange($customerId,$pointGoods->origin_id);
            Db::commit();
            return $this->success([],'成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }

    }

    /**
     * 用户积分商品列表
     *
     * @return string|\think\response\Json
     */
    public function getCustomerPointGoodsList()
    {
        $param = request()->param();
        try {
            $validate  = new CustomerPointValidate();
            if (!$validate->scene('list')->check($param)) {
                return $this->failed(300, $validate->getError());
            }
        }catch (\Exception $e) {
            return $this->error = $e->getMessage();
        }
        $customerId = $param['customer_id'];
        $result = Db::name('customer_point_goods_buy')->alias('a')
            ->field('a.id,a.point_goods_id,b.goods_name,a.status,a.start_time,a.end_time,a.use_time,a.created_at,c.name')
            ->join('customer_point_goods b','a.point_goods_id = b.id','left')
            ->join('shop_person c','a.person_id = c.id','left')
            ->where('customer_id','=',$customerId)
            ->select()->toArray();
        foreach ($result as $key => $value)
        {
            $result[$key]['created_at']=date('Y-m-d H:i:s',$value['created_at']);
            if(!empty($value['start_time']))
            {
                $result[$key]['start_time']=date('Y-m-d H:i:s',$value['start_time']);
            }
            if(!empty($value['end_time']))
            {
                $result[$key]['end_time']=date('Y-m-d H:i:s',$value['end_time']);
            }
            if(!empty($value['use_time']))
            {
                $result[$key]['use_time']=date('Y-m-d H:i:s',$value['use_time']);
            }
        }
        return $this->success($result,'获取成功');

    }

    /**
     * 修改积分来源状态
     *
     * @return \think\response\Json
     */
    public function changeOriginStatus()
    {
        $param = request()->param();
        $id = $param['id'];

        $origin = CustomerPointOriginModel::find($id);
        if(empty($origin))
        {
            return $this->failed(400, "积分来源不存在");
        }
        if($origin->status == 1)
        {
            $origin->status=0;
        }else{
            $origin->status=1;
        }
        $res=$origin->save();
        if($res)
        {
            return $this->success([],'修改成功');
        }else{
            return $this->failed(400, "积分来源状态修改失败");

        }
    }

    /**
     * 使用积分商品
     *
     * @return string|\think\response\Json
     */
    public function usePointGoods()
    {
        $param = request()->param();
        $id = $param['goods_buy_id'];
        $personId = $param['person_id'];
        $pointGoodsBuy = CustomerPointGoodsBuy::find($id);
        if(empty($pointGoodsBuy))
        {
            return $this->failed(400, "积分商品记录不存在");
        }
        if($pointGoodsBuy->status == 0)
        {
            return $this->failed(400, "积分商品已失效");
        }
        if($pointGoodsBuy->status == 2)
        {
            return $this->failed(400, "积分商品已使用");
        }
        $pointGoods = CustomerPointGoods::find($pointGoodsBuy->point_goods_id);
        if(empty($pointGoods))
        {
            return $this->failed(400, "积分商品不存在");
        }
        if($pointGoods->status == 2)
        {
            return $this->failed(500, "积分商品已下架");
        }
        $time = time();
        $date = date('Y-m-d',$time);
        $goodsDetailList = CustomerPointGoodsDetail::where('point_goods_id','=',$pointGoods->id)->select()->toArray();
        $person = PersonModel::find($personId);
        if(empty($person))
        {
            return $this->failed(400, "员工不存在");
        }
        $customer = Customer::find($pointGoodsBuy->customer_id);
        if(empty($customer))
        {
            return $this->failed(400, "客户不存在");
        }
        if($person->shop_id!=$customer->shop_id)
        {
            return $this->failed(400, "门店异常");
        }
        Db::startTrans();
        try {
            switch ($pointGoods->type)
            {
                case 1:{
                    $order = new \app\shop\model\Order();
                    $shop = ShopModel::where('shop_id',$person->shop_id)->find();
                    $store = StoreModel::find($shop->store_id);
                    $user = User::where('shop_person_id','=',$personId)->find();
                    $goodsList = [];
                    foreach ($goodsDetailList as $key => $value)
                    {
                        $goods = Db::name('shop_goods')->alias('a')
                            ->field('a.*,b.name as category_name')
                            ->where('a.id','=',$value['object_id'])
                            ->join('shop_goods_category b','a.category_id = b.id','left')
                            ->find();
                        $projectType=1;
                        $serveData=[];
                        $service_number="";
                        if($goods['is_project']==2)
                        {
                            if($value['service_days']!=0)
                            {
                                $projectType=2;
                                array_push($serveData,$date);
                                array_push($serveData,date('Y-m-d',$time+24*60*60*$value['service_days']));

                            }else{
                                $service_number=$value['service_number'];
                            }
                        }
                        $goodsList[$key]=[
                            'id'=>$goods['id'],
                            'category_id'=>$goods['category_id'],
                            'category_name'=>$goods['category_name'],
                            'create_time'=>$time,
                            'desc'=>"积分商品创建订单",
                            'goods_price'=>$goods['goods_price'],
                            'goods_sn'=>$goods['goods_sn'],
                            'house_code'=>$store->kingdeeCode,
                            'house_code_name'=>$store->name,
                            'is_coupon_goods'=>0,
                            'is_gift'=>0,
                            'is_project'=>$goods['is_project'],
                            'kingdee_code'=>$goods['kingdee_code'],
                            'littleCount'=>0.00,
                            'name'=>$goods['name'],
                            'number'=>$value['number'],
                            'pay_price'=>0,
                            'project_type'=>$projectType,
                            'service_number'=>$service_number,
                            'serveData'=>$serveData,
                            'spec_name'=>$goods['spec_name'],
                            'start_time'=>$date,
                            'end_time'=>date('Y-m-d',$time+24*60*60*$value['service_days']),
                            'status'=>$goods['status'],
                            'unit_code'=>$goods['unit_code'],
                            'unit_name'=>$goods['unit_name'],
                            'zu_name'=>$goods['kingdee_code'].$goods['name']
                        ];
                    }
                    $params = [
                        'business_type'=>2,
                        'consignee'=>$customer->customer_name,
                        'coupon_id'=>"",
                        'coupon_name'=>"",
                        'deal_time'=>$date,
                        'delivery_king'=>$shop->keycode,
                        'delivery_name'=>$shop->shop_name,
                        'description'=>"",
                        'discount_amount'=>0,
                        'experience_id'=>"",
                        'experience_name'=>"",
                        'gift_amount'=>0.00,
                        'house_code'=>$store->kingdeeCode,
                        'house_code_name'=>$store->name,
                        'introduction_id'=>"",
                        'introduction_name'=>"",
                        'is_experience'=>"0",
                        "is_introduction"=>"0",
                        'is_outreach'=>"0",
                        'income_type'=>2,//销售类型：产品
                        'market_id'=>$shop->market_id,
                        'market_name'=>$shop->market_name,
                        'orderTotal'=>"0.00",
                        "outreahc_id"=>"",
                        'outreahc_name'=>"",
                        'order_amount'=>0.00,
                        'order_type'=>2,//补单
                        'pay_amount'=>0.00,
                        'sale_id'=>$personId,
                        'sale_name'=>$shop->shop_owner,
                        'sales_name'=>$shop->market_name,
                        'sales_organization'=>$shop->market_kingdee_code,
                        'sales_policy'=>"",
                        'settlement_name'=>$shop->market_name,
                        'settlement_organization'=>$shop->market_kingdee_code,
                        'shop_id'=>$shop->shop_id,
                        'shop_name'=>$shop->shop_name,
                        'total_amount'=>0.00,
                        'uid'=>$pointGoodsBuy->customer_id,
                        'yhj_id'=>"",
                        'goodsList'=>$goodsList,
                        'operator_id'=>$user->id??0,
                        'shop_transfer_amount'=>0.00,
                        'operator_name'=>$person->name
                    ];
                    $res = $order->addData($params);
                    
                    if($pointGoods->id == '28'){
                        CustomerPointModel::pointChange($pointGoodsBuy->customer_id,'43');
                    }

                    if(!$res)
                    {
                        return $this->failed(400, $order->getError());
                    }
                }
                case 2:{
                    $insertData = [];
                    foreach ($goodsDetailList as $value)
                    {
                        $temp = [
                            'coupon_id'=>$value['object_id'],
                            'customer_id'=>$pointGoodsBuy->customer_id,
                            'create_time'=>$time,
                        ];
                        for ($i=0;$i<$value['number'];$i++)
                        {
                            array_push($insertData,$temp);
                        }
                    }
                    Db::name('coupon_provide_customer')->insertAll($insertData);
                }
            }
            $pointGoodsBuy->status=2;
            $pointGoodsBuy->person_id=$personId;
            $pointGoodsBuy->use_time=$time;
            $pointGoodsBuy->save();
            Db::commit();
            return $this->success([],'成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

    /**
     * 获取用户积分商品兑换单状态
     *
     * @return \think\response\Json|void
     */
    public function getBuyStatus()
    {
        $param = request()->param();
        $id = $param['goods_buy_id'];
        $pointGoodsBuy = CustomerPointGoodsBuy::find($id);
        if(empty($pointGoodsBuy))
        {
            return $this->failed(300, "错误");
        }
        if($pointGoodsBuy->status == 2)
        {
            return $this->success([],'完成');
        }
        if($pointGoodsBuy->status == 1)
        {
            return $this->failed(400, "等待中");
        }
        return $this->failed(300, "错误");

    }

    /**
     * 积分商品使用记录
     *
     * @return \think\response\Json
     */
    public function getPointGoodsEnableLog()
    {
        $param = request()->param();
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $where = [];
        if(!empty($shopIds))
        {
            array_push($where,['b.shop_id','in',$shopIds]);
        }
        if(!empty($param['customer_name']))
        {
            array_push($where,['b.customer_name','like','%'.$param['customer_name'].'%']);
        }
        if(!empty($param['telephone']))
        {
            array_push($where,['b.telephone','=',$param['telephone']]);
        }
        if(!empty($param['shop_id']))
        {
            array_push($where,['b.shop_id','=',$param['shop_id']]);
        }
//        $sql = Db::name('customer_point_log')->alias('a')
//            ->field('b.customer_name,b.telephone,c.shop_name,d.goods_name,a.created_at,e.status,e.use_time,e.id')
//            ->join('customer b','a.customer_id = b.id','left')
//            ->join('shop c','b.shop_id = c.shop_id','left')
//            ->join('customer_point_goods d','a.origin_id = d.origin_id','left')
//            ->join('customer_point_goods_buy e','e.customer_id = b.id','right')
//            ->where($where)
//            ->where('a.origin_id', 'IN', function ($query) {
//                $query->table('xy_customer_point_origin')->where('status', 1)->field('id');
//            });
        $sql = Db::name('customer_point_goods_buy')->alias('a')
            ->field('b.customer_name,b.telephone,c.shop_name,d.goods_name,a.created_at,a.status,a.use_time')
            ->join('customer b','a.customer_id = b.id','left')
            ->join('shop c','b.shop_id = c.shop_id','left')
            ->join('customer_point_goods d','a.point_goods_id = d.id','left')
            ->where($where)
            ->where('a.point_goods_id', 'IN', function ($query) {
                $query->table('xy_customer_point_goods')->field('id');
            });


        $count = $sql->count();
        $list = $sql
            ->order('a.id desc')
            ->page($param['page'], $param['limit'])
            ->select()->toArray();
        $status = [
            "失效","未使用","已使用"
        ];
        foreach ($list as $key=>$value)
        {
            $list[$key]['created_at']=date('Y-m-d H:i:s',$value['created_at']);
            $list[$key]['use_time']=$value['use_time']?date('Y-m-d H:i:s',$value['use_time']):"";
            $list[$key]['status']=$status[$value['status']];
        }
        return $this->success($list,'积分商品使用记录',$count);
    }

}
